<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        v-model="listQuery.name"
        placeholder="请输入排班名称"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
      <el-button
        class="filter-item"
        style="margin-left: 10px;"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate"
      >
        添加
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <el-table-column label="排班ID" prop="id" align="center" width="80" :class-name="getSortClass('id')">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="排班名称" align="center">
        <template slot-scope="{row}">
          <span>{{ row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="上班时间" width="80" align="center">
        <template slot-scope="{row}">
          <span>{{ row.startTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="下班时间" width="80" align="center">
        <template slot-scope="{row}">
          <span>{{ row.endTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="周值班" width="420" align="center">
        <template slot-scope="{row}">
          <el-checkbox-group v-model="row.week" size="mini">
            <el-checkbox-button v-for="weekDay in weeks" :key="weekDay.key" :label="weekDay.key" @click.native.prevent>{{ weekDay.value }}</el-checkbox-button>
          </el-checkbox-group>
        </template>
      </el-table-column>
      <el-table-column label="日期排班" class-name="status-col" width="100">
        <template slot-scope="{row}">
          <el-popover
            placement="right"
            width="200"
            trigger="click"
          >
            <el-table :data="row.day" height="300">
              <el-table-column width="150" label="上班日期">
                <template slot-scope="scope">
                  {{ scope.row }}
                </template>
              </el-table-column>
            </el-table>
            <el-button slot="reference" size="mini">详情</el-button>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button size="mini" type="danger" @click="handleDelete(row,$index)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.pageNum"
      :limit.sync="listQuery.pageSize"
      @pagination="getList"
    />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="left"
        label-width="120px"
        style="width: 600px; margin-left:50px;"
      >
        <el-form-item v-if="['update'].includes(dialogStatus)" label="排班ID" prop="id">
          <el-input v-model="temp.id" :readonly="['update'].includes(dialogStatus)" />
        </el-form-item>
        <el-form-item v-if="['update','create'].includes(dialogStatus)" label="排班名称" prop="name">
          <el-input v-model="temp.name" placeholder="请输入排班名称" />
        </el-form-item>
        <el-form-item
          v-if="['create','update'].includes(dialogStatus)"
          label="上班时间"
          prop="startTime"
        >
          <el-time-picker
            v-model="temp.startTime"
            placeholder="请选择时间"
            value-format="HH:mm:ss"
            type="datetime"
            :readonly="['query'].includes(dialogStatus)"
          />
        </el-form-item>
        <el-form-item
          v-if="['create','update'].includes(dialogStatus)"
          label="下班时间"
          prop="endTime"
        >
          <el-time-picker
            v-model="temp.endTime"
            placeholder="请选择时间"
            value-format="HH:mm:ss"
            type="datetime"
            :readonly="['query'].includes(dialogStatus)"
          />
        </el-form-item>
        <el-form-item v-if="['update','create'].includes(dialogStatus)" label="值班选择-周" prop="week">
          <el-checkbox-group v-model="temp.week" size="mini">
            <el-checkbox-button v-for="weekDay in weeks" :key="weekDay.key" :label="weekDay.key">{{ weekDay.value }}</el-checkbox-button>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item v-if="['update','create'].includes(dialogStatus)" label="值班选择-日期" prop="day">
          <el-date-picker
            v-model="temp.day"
            type="dates"
            value-format="yyyy-MM-dd"
            placeholder="选择一个或多个值班日期"
          />
          <template>
            <el-popover
              placement="right"
              width="200"
              trigger="click"
            >
              <el-table :data="temp.day" height="300">
                <el-table-column width="150" label="上班日期">
                  <template slot-scope="scope">
                    {{ scope.row }}
                  </template>
                </el-table-column>
              </el-table>
              <el-button slot="reference" size="mini">详情</el-button>
            </el-popover>
          </template>
        </el-form-item>
        <el-alert
          title="提醒"
          type="warning"
          description="值班方式：【按周值班】和【按日期值班】，按日期值班优先级高于按周值班"
          show-icon
        />
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确认
        </el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="dialogPvVisible" title="角色分配">
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="confirmData(value)">确认</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination'
import { listDuty, addDuty, removeDuty, modifyDuty } from '@/api/info/duty' // secondary package based on el-pagination
const calendarTypeOptions = [
  { key: 'CN', display_name: 'China' },
  { key: 'US', display_name: 'USA' },
  { key: 'JP', display_name: 'Japan' },
  { key: 'EU', display_name: 'Eurozone' }
]

// arr to obj, such as { CN : "China", US : "USA" }
const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name
  return acc
}, {})

export default {
  name: 'InfoDevice',
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        true: 'success',
        false: 'danger'
      }
      return statusMap[status]
    },
    typeFilter(type) {
      return calendarTypeKeyValue[type]
    }
  },
  data() {
    return {
      renderFunc(h, option) {
        return <span>{ option.key } - { option.label }</span>
      },
      weeks: [
        { key: 1, value: '周一' },
        { key: 2, value: '周二' },
        { key: 3, value: '周三' },
        { key: 4, value: '周四' },
        { key: 5, value: '周五' },
        { key: 6, value: '周六' },
        { key: 7, value: '周日' }
      ],
      list: null,
      total: 0,
      tableKey: 0,
      listLoading: true,
      listQuery: {
        pageNum: 1,
        pageSize: 10,
        name: ''
      },
      rules: {},
      sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
      statusOptions: [{ key: true, text: '启用' }, { key: false, text: '禁用' }],
      temp: {
        id: '',
        name: '',
        week: [],
        day: [],
        startTime: '',
        endTime: ''
      },
      dialogFormVisible: false,
      dialogFormVisible1: true,
      dialogStatus: '',
      textMap: {
        update: '修改',
        create: '添加'
      },
      dialogPvVisible: false,
      downloadLoading: false
    }
  },
  created() {
    this.getList()
  },
  methods: {
    handleChange(value, direction, movedKeys) {
      console.log(value, direction, movedKeys)
    },
    getList() {
      this.listLoading = true
      listDuty(this.listQuery).then(response => {
        this.list = response.data.list
        this.total = response.data.total
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.pageNum = 1
      this.getList()
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        id: '',
        name: '',
        week: [],
        day: [],
        startTime: '',
        endTime: ''
      }
    },
    handleCreate() {
      this.rules = {
        name: [{ required: true, trigger: ['blur', 'change'], message: '排班名称不能为空' }],
        startTime: [{ required: true, trigger: ['blur', 'change'], message: '上班时间不能为空' }],
        endTime: [{ required: true, trigger: ['blur', 'change'], message: '下班时间不能为空' }]
      }
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.listLoading = true
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          addDuty(this.temp).then(response => {
            const { data } = response
            this.temp.id = data.id
            this.temp.createTime = data.createTime
            this.list.unshift(this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '添加成功',
              type: 'success',
              duration: 3000
            })
            this.listLoading = false
          })
        }
      })
    },
    handleUpdate(row) {
      this.rules = {
        name: [{ required: true, trigger: ['blur', 'change'], message: '排班名称不能为空' }],
        startTime: [{ required: true, trigger: ['blur', 'change'], message: '上班时间不能为空' }],
        endTime: [{ required: true, trigger: ['blur', 'change'], message: '下班时间不能为空' }]
      }
      this.temp = Object.assign({}, row) // copy obj
      this.temp.timestamp = new Date(this.temp.timestamp)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.listLoading = true
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          modifyDuty(this.temp).then(() => {
            const index = this.list.findIndex(v => v.id === this.temp.id)
            this.list.splice(index, 1, this.temp)
            this.total = this.total + 1
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '修改成功',
              type: 'success',
              duration: 2000
            })
            this.listLoading = false
          })
        }
      })
    },
    handleDelete(row, index) {
      removeDuty({ id: row.id }).then(() => {
        this.dialogFormVisible = false
        this.$notify({
          title: '成功',
          message: '删除成功',
          type: 'success',
          duration: 2000
        })
        this.list.splice(index, 1)
      })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['timestamp', 'title', 'type', 'importance', 'status']
        const filterVal = ['timestamp', 'title', 'type', 'importance', 'status']
        const data = this.formatJson(filterVal)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'table-list'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    }
  }
}
</script>
